/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistencia;

import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.DataInputStream;
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.Iterator;

/**
 *
 * @author jessica.rodrigues
 */
public abstract class DAO {
	protected final int INDEX_KEY = 0;

	private String path;
	private ArrayList<String[]> buffer;
	private boolean loaded;

	public DAO(String path) {
		this.path = path;
		this.loaded = false;
		this.buffer = new ArrayList<String[]>();
	}

	protected ArrayList<String[]> getListString() {
		if (!this.loaded) {
			try {
				this.buffer.clear();

				// Open the file that is the first 
				// command line parameter
				FileInputStream fstream = new FileInputStream(this.path);
				// Get the object of DataInputStream
				DataInputStream in = new DataInputStream(fstream);
				BufferedReader br = new BufferedReader(new InputStreamReader(in));
				String strLine;
				//Read File Line By Line
				while ((strLine = br.readLine()) != null) {
					// Print the content on the console
					String[] dataList = strLine.split(";");
					this.buffer.add(dataList);
				}
				//Close the input stream
				in.close();

				this.loaded = true;
			} catch (Exception e) {//Catch exception if any
				System.err.println("Error: " + e.getMessage());
			}
		}

		return this.buffer;
	}

	private void storeBuffer(String[] data) {
		ArrayList<String[]> buffer = this.getListString();
		if (data[INDEX_KEY] != null) {
			int size = buffer.size();
			for (int i = 0; i < size; i++) {
				if (buffer.get(i)[INDEX_KEY].equals(data[INDEX_KEY])) {
					buffer.set(i, data);
					return;
				}
			}
		}
		buffer.add(data);
	}

	private String getCsv() {
		ArrayList<String[]> buffer = this.getListString();

		StringBuilder result = new StringBuilder();
		for (String[] data : this.buffer) {
			result.append(data[0]);
			for (int j = 1; j < data.length; j++) {
				result.append(';');
				result.append(data[j]);
			}
			result.append("\n");
		}
		return result.toString();
	}
	
	protected void storeFile() {
		try {
			FileWriter fileWriter = new FileWriter(this.path);
			fileWriter.write(this.getCsv());
			fileWriter.close();
		} catch (Exception e) {
		}
	}

	/**
	 * Insere um novo registro caso nao exista e altera o valor caso ja exista.
	 * A posicao "0" determina se o registro ja existe.
	 *
	 * @param data Dados a serem inseridos.
	 */
	protected void store(String[] data) {
		this.storeBuffer(data);
		this.storeFile();
	}
	
	protected void remove(String key) {
		this.remove(key, INDEX_KEY);
	}

	protected void remove(String value, int position) {
		ArrayList<String[]> buffer = this.getListString();
		Iterator<String[]> iterator = buffer.iterator();
		String[] dataList = iterator.next();
		while(dataList != null) {
			if(dataList[position].equals(value)) {
				iterator.remove();
				break;
			}
			dataList = iterator.next();
		}
		this.storeFile();
	}

	protected abstract int getNextCodigo();
}